package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    ShopTypeMapper shopTypeMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.根据Key值获取Redis中的缓存值
        Set<String> members = stringRedisTemplate.opsForSet().members("shop::type::set");
        log.info("中Redis中获取到的数据是" + members);
        //2.判断是否有值，有值则返回
        if (!members.isEmpty()) {
            List<ShopType> shopTypeList = new ArrayList<>();
            members.forEach(a -> shopTypeList.add(JSONUtil.toBean(a, ShopType.class)));
            return Result.ok(shopTypeList);
        }
        //3.没有值则查询数据库
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByAsc("sort");
        List<ShopType> shopTypeListDate = shopTypeMapper.selectList(queryWrapper);
        //4.将查到的数据缓存到redis中
        shopTypeListDate.forEach(shopType -> stringRedisTemplate.opsForSet().add("shop::type::set",JSONUtil.toJsonStr(shopType)));
        if (null == shopTypeListDate) {
            return Result.fail("数据为空");
        }
        return Result.ok(shopTypeListDate);
    }
}
